package com.power.using.sharlockchat.application;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.StrictMode;
import android.support.annotation.NonNull;
import android.support.multidex.MultiDex;
import android.support.v7.app.AppCompatDelegate;
import android.util.Log;

import com.igexin.sdk.PushManager;
import com.power.using.sharlockchat.R;
import com.power.using.sharlockchat.bean.ShowBean;
import com.power.using.sharlockchat.receiver.KeepAliveBroadcast;
import com.power.using.sharlockchat.service.DemoIntentService;
import com.power.using.sharlockchat.service.DemoPushService;
import com.power.using.sharlockchat.service.HeartBeatService;
import com.power.using.sharlockchat.service.KeepAliveServiceOne;
import com.power.using.sharlockchat.store.PersistentCookieStore;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.sunfusheng.daemon.DaemonHolder;
import com.zhy.autolayout.config.AutoLayoutConifg;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.JavaNetCookieJar;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by 聪明一只哈 on 2019/1/17.
 * Time: 2019/1/17  16:43
 */
public class MyApplication extends Application {

    public static Context sContext;
    private static MyApplication sApplication;
    private static List<ShowBean> showBeanList=new ArrayList<>();


    //刷新头  下拉刷新框架配置
    static {
        //启用矢量图兼容
        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                //全局设置主题颜色（优先级第二低，可以覆盖 DefaultRefreshInitializer 的配置，与下面的ClassicsHeader绑定）
                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);

                return new ClassicsHeader(context).setTimeFormat(new DateFormat() {
                    @Override
                    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {

                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String time = format.format(date);

                        return toAppendTo.append(time);
                    }

                    @Override
                    public Date parse(String source, ParsePosition pos) {
                        return null;
                    }
                });
            }
        });
    }

    @Override
    public void onCreate() {
        super.onCreate();
        sApplication = this;
        sContext = getApplicationContext();

        //解决FileUriExposedException。  WPS
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }



        //使用autolayot
        AutoLayoutConifg.getInstance().useDeviceSize().init(this);
        //初始化okhttp
        initOKHttps();

        PushManager.getInstance().initialize(this.getApplicationContext(), DemoPushService.class);
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), DemoIntentService.class);

        //MainActivity开启后台服务
        DaemonHolder.init(this, HeartBeatService.class);

        //开启系统时间广播(动态注册,不能静态注册)
        //部分机型会屏蔽时间广播
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_USER_PRESENT);//android.intent.action.USER_PRESENT
        intentFilter.addAction(Intent.ACTION_TIME_TICK);//系统时间，每分钟发送一次
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);//屏幕打开（解锁），
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);//屏幕关闭
        KeepAliveBroadcast myBroadcast = new KeepAliveBroadcast();
        registerReceiver(myBroadcast, intentFilter);
        startMyService();


    }

    public static List<ShowBean> getShowBeanList() {
        return showBeanList;
    }

    public static void setShowBeanList(List<ShowBean> showBeanList) {
        MyApplication.showBeanList = showBeanList;
    }

    public static Context getmContext() {
        return sContext;
    }
    /**
     * 开启双服务
     */
    private void startMyService() {
        Intent serviceOne = new Intent();
        serviceOne.setClass(this, KeepAliveServiceOne.class);
        startService(serviceOne);
    }

    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }

    private void initOKHttps() {
        CookieHandler cookieHandler = new CookieManager(new PersistentCookieStore(getApplicationContext()),
                CookiePolicy.ACCEPT_ALL);


        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addNetworkInterceptor(new MyApplication.CacheInterceptor())
                .writeTimeout(30000L, TimeUnit.SECONDS)
                .readTimeout(30000L, TimeUnit.SECONDS)
                .connectTimeout(30000L, TimeUnit.SECONDS)
                .addInterceptor(logging)
                .cookieJar(new JavaNetCookieJar(cookieHandler))
                .build();

        OkHttpUtils.initClient(okHttpClient);


    }

    public class CacheInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            int code = response.code();
            Log.e("显示", "code值" + code);
            Response response1 = response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    //cache for 30 days
                    .header("Cache-Control", "max-age=" + 3600 * 24 * 30)
                    .build();
            return response1;
        }
    }

    public static MyApplication getApplicationIntstance() {
        return sApplication;
    }


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }



}
